#include <QApplication>
#include <QThread>
#include <QDir>
#include <QtHttpServer/QHttpServer>
#include "mwlserver.h"
#include "settings.h"
#include "formatter.h"
#include "logging.h"
#include "idreader.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    Logging::initialize();
    const Formatter &f = Formatter::Singleton();
    const IDReader idr;
    QHttpServer http;
    const Settings &s = Settings::Singleton();
    http.route(s.httpRoutePath(), [&f] (const QHttpServerRequest &request) {

        if (request.method() == QHttpServerRequest::Method::Options) {
            QHttpServerResponse rs(QHttpServerResponse::StatusCode::Accepted);
            rs.setHeader("Access-Control-Allow-Origin","*");
            rs.setHeader("Access-Control-Allow-Methods","*");
            rs.setHeader("Access-Control-Allow-Headers","*");
            return rs;
        }
        return f.processHttpRequest(request.body());
    });
    int port = http.listen(QHostAddress::Any, s.httpPort());
    qInfo() << "Http server listening on port: " << port;

    QThread *mst = new QThread();
    MwlServer *ms = new MwlServer(s.scpPort(), s.scpDbPath());
    ms->moveToThread(mst);
    QObject::connect(mst, &QThread::started, ms, &MwlServer::start);
    QObject::connect(mst, &QThread::finished, mst, &QThread::deleteLater);
    mst->start();

    return a.exec();
}
